<template>
  <div
    v-loading="isSavePortLoading"
    element-loading-text="处理中..."
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <div class="tip">
      <span>为保证系统稳定，新添加的帐号，48小时后才可删除；</span>
      <span>如果要修改帐号，请先删除旧帐号再添加新帐号；</span>
    </div>
    <el-form ref="form" :model="bindingAccount" :rules="rules" label-width="100px" size="mini">
      <el-form-item label="手机" prop="account" :error="formError.account">
        <el-input
          v-model.trim="bindingAccount.account"
          placeholder="账号"
          style="width: 200px"
          :disabled="handleType === 'edit'"
          :suffix-icon="handleType === 'edit' ? 'el-icon-lock' : ''"
          :maxlength="11"
        ></el-input>
      </el-form-item>

      <div class="instruction" >
        <span @click="handleClick" style="cursor: pointer;">请点击跳转至幸福里经纪人登录页面，</span><span class="red">填写手机号并发送验证码， 切记把验证码填入本页面。</span>
      </div>
      <el-form-item label="验证码" prop="telcode" :error="formError.telcode">
        <el-input v-model.trim="bindingAccount.telcode" placeholder="请输入手机验证码" style="width: 200px"></el-input>
      </el-form-item>

      <el-form-item class="d-flex jc-end">
        <el-button type="primary" :disabled="submitDisable" round @click="submit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { phoneNumberCheck } from '@/utils/utilsNew';

export default {
  name: 'PortManagementXflStore',

  components: {},

  props: {
    handleType: {
      type: String,
      default: ''
    },
    echoData: {
      type: Object,
      default() {
        return {};
      }
    }
  },

  data() {
    this.timer = null; // 计时器
    return {
      isSavePortLoading: false,
      submitDisable: true,
      bindingAccount: {
        account: '',
        telcode: ''
      },
      formError: {
        account: '',
        telcode: ''
      }, // 异步错误
      rules: {
        account: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value === '') {
                callback(new Error('手机号不能为空'));
              } else if (!phoneNumberCheck(value)) {
                callback(new Error('请输入正确的手机号'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        telcode: [{ required: true, message: '验证码不能为空', trigger: 'blur' }]
      }
    };
  },

  created() {},

  computed: {},

  watch: {
    bindingAccount: {
      handler(value) {
        if (this.submitDisable) {
          if (Object.values(value).some((v) => !v)) return;
        }
        this.$refs['form'].validate((valid) => {
          this.submitDisable = !valid;
        });
      },
      deep: true
    },
    echoData: {
      handler: function(val) {
        const { handleType } = this;
        if (!val || handleType !== 'edit') return;
        const { account } = val;
        Object.assign(this.bindingAccount, {
          account: account || ''
        });
      },
      immediate: true
    }
  },

  methods: {
    handleClick() {
      window.open('https://vip.xingfukeapp.com/login', '_blank');
    },
    // 提交表单
    submit() {
      const { handleType } = this;
      switch (handleType) {
        case 'add':
          this.addAccount();

          break;
        case 'edit':
          this.editAccount();
          break;
      }
    },
    // 添加端口
    async addAccount() {
      try {
        this.isSavePortLoading = true;
        const { account, telcode } = this.bindingAccount;

        const { portType } = this.echoData;
        const res = await this.$api.addAccount({
          portType,
          account,
          city: '昆山', //临时
          password: '-',
          telcode
        });
        const result = res.content || {};
        gio('track', 'bindPortResult', {
          handle_type: 'add',
          port_channel: portType,
          result_code: result.statusCode,
          result_msg: result.reason
        });
        if (res && res.isSuccess && res.content.status === '1') {
          this.$message.success('绑定成功!');
          this.$emit('portChange');
          this.$emit('close');
        } else {
          this.solvePortError({
            errorCode: result.statusCode,
            errorMessage: result.reason || '绑定失败，请稍后再试~',
            errorParams: result.accountVerifyVo || {}
          });
        }
      } catch (error) {
        console.log('error: ' + error);
      } finally {
        this.isSavePortLoading = false;
      }
    },

    // 更新端口
    async editAccount() {
      try {
        this.isSavePortLoading = true;
        const { account, telcode } = this.bindingAccount;
        const { id, portType } = this.echoData;
        const res = await this.$api.updateAccount({
          id,
          portType,
          account,
          city: '昆山', //临时
          password: '-',
          telcode
        });
        const result = res.content || {};
        gio('track', 'bindPortResult', {
          port_id: id,
          port_channel: portType,
          handle_type: 'edit',
          result_code: result.statusCode,
          result_msg: result.reason
        });
        if (res && res.isSuccess && res.content.status === '1') {
          this.$message.success('修改成功!');
          this.$emit('portChange');
          this.$emit('close');
        } else {
          this.solvePortError({
            errorCode: result.statusCode,
            errorMessage: result.reason || '保存失败，请稍后再试~',
            errorParams: result.accountVerifyVo || {}
          });
        }
      } catch (error) {
        console.log('error: ' + error);
      } finally {
        this.isSavePortLoading = false;
      }
    },

    // 处理端口错误
    solvePortError({ errorCode, errorMessage, errorParams = {} }) {
      this.$message.error(errorMessage || '操作失败，请稍后再试~');

      // 端口需要验证码校验
      if (['account_login.check_mobile'].indexOf(errorCode) !== -1) {
        this.bindingAccount.telcode = ''
        return;
      }
      // 账号错误
      if (
        [
          'account_login.account_exist',
          'account_login.port_exist',
          'account_login.account_time_bind',
          'account_login.name_or_pass_fail'
        ].indexOf(errorCode) !== -1
      ) {
        this.bindingAccount.account = ''
        this.bindingAccount.telcode = ''
        return;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
@import '~@/styles/colors.scss';

.tip {
  display: flex;
  flex-direction: column;
  margin-top: -10px;
  margin-bottom: 20px;
  padding: 10px 24px;
  font-size: 10px;
  line-height: 2;
  color: #ee4d4d;
  font-weight: 700;
  background: #fff4f4;
}

.instruction {
  margin-left: 64px;
  margin-bottom: 18px;
  color: $blue;
  .red {
    color: $red;
  }
}
</style>
